//
//  CZComposeTextView.swift
//  Weibo28
//
//  Created by Apple on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//  自定义textview

//  实现看到xib效果
@IBDesignable
class CZComposeTextView: UITextView {

    //  MARK:   - 懒加载
    //  占位文字label
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "听说下雨天音乐跟辣条更配哟~"
        label.textColor = UIColor.lightGrayColor()
        label.numberOfLines = 0
        
        return label
    }()
    //  设置占位文字 ,让属性在xib中显示
    @IBInspectable var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder

        }
    }
    
    //  重写font
    override var font: UIFont? {
        didSet {
            
            if font == nil {
                return
            }
            
            placeHolderLabel.font = font
        }
    }
    
    //  重写text
    override var text: String? {
        didSet {
            placeHolderLabel.hidden = hasText()
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        //  监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChage", name: UITextViewTextDidChangeNotification, object: nil)
        
    }
    //  支持xib
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
        //  监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChage", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    private func setupUI() {
        addSubview(placeHolderLabel)
        
        //  使用系统的约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //  指定位置
        placeHolderLabel.frame.origin.x = 5
        placeHolderLabel.frame.origin.y = 8
    }
    
    @objc private func textChage() {
//        if hasText() {
//            placeHolderLabel.hidden = true
//        } else {
//            placeHolderLabel.hidden = false
//        }
        
        placeHolderLabel.hidden = hasText()
        
    }
    
    //  移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}
